<template>
    <div>
        <table class="table">
            <tbody class="table">
                <tr>
                    <td><a style="color: red;">*</a>食谱标题</td>
                    <td>
                        <input type="text" v-model="data.title">
                    </td>
                </tr>
                <tr>
                    <td><a style="color: red;">*</a>食品分类</td>
                    <td>
                        <select v-model="data.tid">
                            <option :value="0">==请选择==</option>
                            <option v-for="d in showdata" :value="d.tid">{{ d.tName }}</option>
                        </select>
                    </td>
                </tr>
                <tr>
                    <td><a style="color: red;">*</a>食品图片</td>
                    <td>
                        <input type="file" @change="up">
                        <img :src="'https://localhost:7220'+data.foodImg" style="width: 60px;height: 60px;">
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td colspan="2">
                        <button type="button" class="btn btn-outline-info" @click="add">添加食品</button>
                        <button type="button" class="btn btn-outline-info" @click="back">返回</button>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</template>

<script setup lang="ts">
import axios from 'axios';
import { ref,onMounted } from 'vue';
import { useRouter } from 'vue-router';
onMounted(() => {
    showdd();
})

const showdata=ref([{
    "tid": 0,
    "tName": ""
}])

const showdd=()=>{
    axios.get("https://localhost:7220/api/Food/FoodTypes").then(res=>{
        showdata.value=res.data;
    })
}
const up=(a:any)=>{
    var f=a.target.files[0]
    console.log(f.type)
    var fd=new FormData()
    fd.append("files",f);
    axios.post("https://localhost:7220/api/Food/Upload",fd).then(res=>{
        data.value.foodImg=res.data;
    })
}

const data=ref({
    "fid": 0,
  "title": "",
  "tid": 0,
  "foodImg": ""
})
const router=useRouter();

const add=()=>{
    if(data.value.title==""){
        alert("标题不能为空")
        return;
    }
    if(data.value.tid==0){
        alert("食品分类必须选择")
        return;
    }
    if(data.value.foodImg==""){
        alert("图片必须上传")
        return;
    }
    axios.post("https://localhost:7220/api/Food/AddFood",data.value).then(res=>{
        if(res.data>0){
            alert("添加成功");
            router.push({
                path:'/ShowView'
            })
        }
    })
}
const back=()=>{
    router.push({
        path:'/'
    })
}

</script>

<style scoped>

</style>